package com.cxs.preferencestest.slice;

import com.cxs.preferencestest.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

import java.util.Map;
import java.util.Set;

public class MainAbilitySlice extends AbilitySlice {

    DatabaseHelper helper;
    Preferences preferences;

    private class PreferencesObserverImpl implements Preferences.PreferencesObserver {
        @Override
        public void onChange(Preferences preferences, String s) {
            System.out.println(s);
        }
    }

    PreferencesObserverImpl observer = new PreferencesObserverImpl();

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        findComponentById(ResourceTable.Id_btn_write).setClickedListener(c -> writeData());
        findComponentById(ResourceTable.Id_btn_read).setClickedListener(c -> readData());
        findComponentById(ResourceTable.Id_btn_delete).setClickedListener(c -> deleteData());
        findComponentById(ResourceTable.Id_btn_remove).setClickedListener(c -> removePreference());
        findComponentById(ResourceTable.Id_btn_removeFile).setClickedListener(c -> deletePref());

        helper = new DatabaseHelper(this);
        // 获取 Preferences 实例
        preferences = helper.getPreferences("preferences_test");
        // 注册观察者
        preferences.registerObserver(observer);
    }

    private void deletePref() {
        boolean preferences = helper.deletePreferences("preferences_test");
        System.out.println(preferences);
    }

    // 移除内存中的 Preferences 实例
    private void removePreference() {
        helper.removePreferencesFromCache("preferences_test");
    }

    // 删除数据
    private void deleteData() {
        preferences.delete("intkey");
    }

    // 读数据
    private void readData() {
        String test1 = preferences.getString("test1", "你好，鸿蒙");
        System.out.println(test1);
    }

    // 写数据
    private void writeData() {
        preferences.putString("test1", "Hello HarmonyOS");
        preferences.flush();
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    protected void onStop() {
        super.onStop();
        preferences.unregisterObserver(observer);
    }
}
